package examples

import org.offsync.async.AsyncSelector
import org.offsync.async.AsyncServerSocket
import org.offsync.rich._
import org.offsync.util.Window

object EchoServer {
  val portRange: Seq[Int] = 2000 to 3000
  
  def main(args: Array[String]): Unit = {
    if (args.length != 2) {
      System.err.println("Usage: server <port> <runtime>")
      exit(1)
    }
    
    val port = args(0).toInt
    val runtime = args(1).toInt
    
    new AsyncSelector().using { ioService =>
      AsyncServerSocket.open("localhost", portRange) { completion =>
        val (serverChannel, port) = completion()
        serverChannel.accept(ioService) { getSocket =>
          try {
            for (sessionChannel <- getSocket()) {
              val window = Window to (new Array[Byte](100))
              def performSessionRead(): Unit = {
                sessionChannel.readSome(ioService, window) { getBytesRead =>
                  try {
                    val bytesRead = getBytesRead()
                    if (bytesRead < 0) {
                    } else {
                      val dataWindow = window.until(bytesRead)
                      val dataString = dataWindow.asString
                      sessionChannel.writeSome(ioService, window.until(bytesRead)) { getBytesWritten =>
                        try {
                          val bytesWritten = getBytesWritten()
                          performSessionRead()
                        } catch {
                          case e => System.err.println("exception: " + e)
                        }
                        false
                      }
                    }
                  } catch {
                    case e => System.err.println("exception: " + e)
                  }
                  false
                }
              }
              performSessionRead()
            }
          } catch {
            case e => System.err.println("exception: " + e)
          }
          false
        }
        println("runtime: " + runtime)
        runtime.seconds.sleep()
      }
    }
  }
}
